﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using Moonwish.Core;
using Moonwish.Core.DataAccess;
using Moonwish.Foundation.DataEntity;

namespace Moonwish.Foundation.DataAccess.SqlServer.ValueObjectCmd
{
    public class QueryDataCommand : QueryCommand<V_FDT_ValueObject>
    {
        public QueryDataCommand(DbContext dbContext, Request request)
            : base(dbContext, request)
        {
            Map.Add("ValueObject.ClassId".ToLower(), "ValueObjectClassId");
            Map.Add("ValueObject.Id".ToLower(), "ValueObjectId");
            Map.Add("ValueObject.Name".ToLower(), "Name");
            Map.Add("ValueObject.Code".ToLower(), "Code");
            Map.Add("ValueObject.Status".ToLower(), "DataStatus");
        }

        public override List<V_FDT_ValueObject> Execute()
        {
            return DbContext.Set<V_FDT_ValueObject>().SqlQuery(BuildSql()).ToList();
        }

        protected override string BuildSql()
        {
            var sql = new StringBuilder();
            sql.Append("select * from [V_FDT_ValueObject] t where 1 = 1 ");
            if (Request.Items != null)
            {
                foreach (var item in Request.Items)
                {
                    if (String.IsNullOrEmpty(item.FieldName))
                    {
                        throw new InvalidOperationException("查询条件的字段名称不能为空。");
                    }
                    if (item.Values == null || item.Values.Length == 0)
                    {
                        throw new InvalidOperationException("查询条件的值不能为空。");
                    }
                    string column = ToDbColumn(item.FieldName.ToLower());
                    sql.Append(String.Format(" {0} {1} {2} {3} ", item.Relation, column, item.GetOperator(), item.GetValues()));
                }
            }
            return sql.ToString();
        }
    }
}
